const express = require('express')
const router = express.Router()
const userDB = require('../../db/user')

// 登录接口
router.post('/', async (req, res) => {
  let {user, pass} = req.body
  let userReg = /^[^\s]{2,8}$/,
      passReg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/

  if(!userReg.test(user) || !passReg.test(pass)){
    return res.send({
      code: 1,
      msg: '数据格式错误'
    })
  }

  let doc = await userDB.findOne({user})
  if(!doc){
    return res.send({
      code: 2,
      msg: '用户不存在'
    })
  }

  if(doc.pass !== pass){
    return res.send({
      code: 3,
      msg: '密码不正确'
    })
  }

  let data = {
    _id: doc._id,
    user: doc.user,
    avatar: doc.avatar,
    isAdmin: doc.isAdmin,
    regDate: doc.regDate,
    msgPermissions: doc.msgPermissions
  }
  // 配置session
  req.session.userInfo = data
  res.send({
    code: 0,
    msg: '登录成功',
    data
  })  
})

// 检测是否登录
router.post('/check', async (req, res) => {
  if(req.session.userInfo){
    res.send({
      code: 0,
      msg: '用户已登录',
      data: req.session.userInfo
    })
  }else{
    res.send({
      code: 1,
      msg: '用户未登录',
      data: {}
    })
  }
})

// 退出登录
router.post('/logout', async(req, res) => {
  req.session.destroy() // 销毁session
  res.send({
    code: 0,
    msg: '退出登录成功'
  })
})

module.exports = router